#!/usr/bin/env node

const https = require('https');

const url = 'https://api.github.com/search/repositories?q=user:' + (process.argv[2] ?? 'wangding');
const log = console.log;
const headers = { 'User-Agent': '02-get-repos.js' };

https.get(url, { headers }, res => {
  let data = '';
  res.setEncoding('utf8');
  res.on('data', chunk => data += chunk);
  res.on('end', () => {
    try {
      const response = JSON.parse(data);
      // 检查items是否存在
      if (!response.items) {
        log('未找到仓库信息。');
        return;
      }
      const reps = response.items;
      log('Total:', reps.length);
      log('==========================');
      reps.forEach((rep, index) => {
        log(`${index + 1}\t${rep.name}`);
      });
    } catch (error) {
      log('解析数据时发生错误:', error);
    }
  });
}).on('error', error => {
  log('请求过程中发生错误:', error);
});
